package com.xinting.piano.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.widget.ToggleButton;

import com.xinting.piano.data.PColor;

/**
 * Created by wuxinting on 15/11/19.
 * 切换的button
 * 主要是更换样式
 */
public class PToggleButton extends ToggleButton {

    private Paint paint;

    public PToggleButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    public PToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public PToggleButton(Context context) {
        super(context);
        initialize();
    }

    private void initialize() {
        CharSequence on = getTextOn();
        CharSequence off = getTextOff();
        CharSequence text = on + "   " + off;
        setTextOff(text);
        setTextOn(text);
        setText(text);

        paint = new Paint();
        paint.setColor(PColor.METAL_BLACK);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onFinishInflate() {
    //重新设置圆角，使成为半圆
        float h = getHeight();
        Drawable drawable = getBackground();
        if (drawable instanceof GradientDrawable) {
            GradientDrawable gradientDrawable = (GradientDrawable) drawable;
            gradientDrawable.setCornerRadius(h / 2);
        }
        super.onFinishInflate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float h = getHeight();

        //遮盖
        float w = getWidth();
        if (isChecked()) {
            canvas.drawCircle(w - h / 2, h / 2, h / 2, paint);
            canvas.drawRect(w / 2, 0, w - h / 2, h, paint);
        } else {
            canvas.drawCircle(h / 2, h / 2, h / 2, paint);
            canvas.drawRect(h / 2, 0, w / 2, h, paint);
        }
    }
}
